<template>
  <div class="services-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>服务管理</h1>
        <p>管理您发布的洗护服务，让客户更容易找到您</p>
      </div>
      <div class="header-actions">
        <el-button @click="showServiceInsights">
          <el-icon><TrendCharts /></el-icon>
          服务洞察
        </el-button>
        <el-button type="primary" @click="showServiceDialog">
          <el-icon><Plus /></el-icon>
          发布新服务
        </el-button>
      </div>
    </div>

    <!-- 服务统计 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <el-card class="stat-card" @click="filterByStatus('ACTIVE')">
          <div class="stat-content">
            <div class="stat-icon active">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.active }}</div>
              <div class="stat-label">已上架服务</div>
              <div class="stat-trend" v-if="serviceStats.activeTrend">
                <el-icon class="trend-icon" :class="serviceStats.activeTrend > 0 ? 'trend-up' : 'trend-down'">
                  <component :is="serviceStats.activeTrend > 0 ? 'TrendCharts' : 'Bottom'" />
                </el-icon>
                <span class="trend-text">{{ Math.abs(serviceStats.activeTrend) }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" @click="filterByStatus('INACTIVE')">
          <div class="stat-content">
            <div class="stat-icon inactive">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.inactive }}</div>
              <div class="stat-label">已下架服务</div>
              <div class="stat-trend" v-if="serviceStats.inactiveTrend">
                <el-icon class="trend-icon" :class="serviceStats.inactiveTrend > 0 ? 'trend-up' : 'trend-down'">
                  <component :is="serviceStats.inactiveTrend > 0 ? 'TrendCharts' : 'Bottom'" />
                </el-icon>
                <span class="trend-text">{{ Math.abs(serviceStats.inactiveTrend) }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" @click="showOrderAnalysis">
          <div class="stat-content">
            <div class="stat-icon orders">
              <el-icon><List /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serviceStats.totalOrders }}</div>
              <div class="stat-label">总订单数</div>
              <div class="stat-trend" v-if="serviceStats.ordersTrend">
                <el-icon class="trend-icon" :class="serviceStats.ordersTrend > 0 ? 'trend-up' : 'trend-down'">
                  <component :is="serviceStats.ordersTrend > 0 ? 'TrendCharts' : 'Bottom'" />
                </el-icon>
                <span class="trend-text">{{ Math.abs(serviceStats.ordersTrend) }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" @click="showRevenueAnalysis">
          <div class="stat-content">
            <div class="stat-icon revenue">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(serviceStats.totalRevenue) }}</div>
              <div class="stat-label">总收入</div>
              <div class="stat-trend" v-if="serviceStats.revenueTrend">
                <el-icon class="trend-icon" :class="serviceStats.revenueTrend > 0 ? 'trend-up' : 'trend-down'">
                  <component :is="serviceStats.revenueTrend > 0 ? 'TrendCharts' : 'Bottom'" />
                </el-icon>
                <span class="trend-text">{{ Math.abs(serviceStats.revenueTrend) }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 服务标签页 -->
    <el-card class="services-list-card">
      <template #header>
        <div class="card-header">
          <div class="header-tabs">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
              <el-tab-pane label="已发布服务" name="published">
                <template #label>
                  <span>已发布服务 ({{ publishedServices.length }})</span>
                </template>
              </el-tab-pane>
              <el-tab-pane label="草稿箱" name="drafts">
                <template #label>
                  <span>草稿箱 ({{ draftServices.length }})</span>
                </template>
              </el-tab-pane>
              <el-tab-pane label="审核中" name="pending">
                <template #label>
                  <span>审核中 ({{ pendingServices.length }})</span>
                </template>
              </el-tab-pane>
              <el-tab-pane label="已驳回" name="rejected">
                <template #label>
                  <span>已驳回 ({{ rejectedServices.length }})</span>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="header-filters">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索服务名称或描述"
              style="width: 200px;"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px;" clearable>
              <el-option label="全部" value="" />
              <el-option label="已上架" value="ACTIVE" />
              <el-option label="已下架" value="INACTIVE" />
            </el-select>
            <el-select v-model="filterType" placeholder="类型筛选" style="width: 120px;" clearable>
              <el-option label="全部" value="" />
              <el-option
                v-for="(text, type) in SERVICE_TYPE_TEXT"
                :key="type"
                :label="text"
                :value="type"
              />
            </el-select>
            <el-button @click="showAdvancedFilter" :icon="Filter">
              高级筛选
            </el-button>
            <el-select v-model="sortBy" placeholder="排序方式" style="width: 120px;">
              <el-option label="默认排序" value="default" />
              <el-option label="价格升序" value="price-asc" />
              <el-option label="价格降序" value="price-desc" />
              <el-option label="评分降序" value="rating-desc" />
              <el-option label="订单量降序" value="orders-desc" />
              <el-option label="收入降序" value="revenue-desc" />
              <el-option label="创建时间" value="create-time" />
            </el-select>
            <el-dropdown @command="handleCreateService">
              <el-button type="primary" :icon="Plus">
                发布新服务
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="blank">空白服务</el-dropdown-item>
                  <el-dropdown-item divided command="template">从模板创建</el-dropdown-item>
                  <el-dropdown-item command="copy">复制现有服务</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              v-if="selectedServices.length > 0"
              type="warning"
              @click="showBatchActions"
            >
              批量操作 ({{ selectedServices.length }})
            </el-button>
          </div>
        </div>
      </template>

      <!-- 快速操作工具栏 -->
      <div class="quick-actions-toolbar" v-if="filteredServices.length > 0">
        <div class="toolbar-left">
          <span class="result-count">共找到 {{ filteredServices.length }} 个服务</span>
          <el-divider direction="vertical" />
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="selectAll"
            @change="handleSelectAll"
          >
            全选
          </el-checkbox>
        </div>
        <div class="toolbar-right">
          <el-button-group>
            <el-button size="small" @click="refreshServices" :icon="Refresh">
              刷新
            </el-button>
            <el-button size="small" @click="exportServices" :icon="Download">
              导出
            </el-button>
            <el-button size="small" @click="showBulkEdit" :disabled="selectedServices.length === 0">
              批量编辑
            </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="services-grid">
        <div
          v-for="service in filteredServices"
          :key="service.id"
          class="service-card"
          :class="{ 'selected': selectedServices.includes(service.id) }"
        >
          <div class="service-header">
            <div class="service-select">
              <el-checkbox
                :model-value="selectedServices.includes(service.id)"
                @change="toggleServiceSelection(service.id)"
              />
            </div>
            <div class="service-type-icon" :class="getServiceIconClass(service.type)">
              <el-icon><component :is="getServiceIcon(service.type)" /></el-icon>
            </div>
            <div class="service-status">
              <el-tag :type="getServiceStatusColor(service.status)" size="small">
                {{ SERVICE_STATUS_TEXT[service.status] || '未知状态' }}
              </el-tag>
            </div>
          </div>
          
          <div class="service-content">
            <h3>{{ service.name }}</h3>
            <p class="service-description">{{ service.description }}</p>
            
            <div class="service-details">
              <div class="detail-item">
                <span class="label">价格：</span>
                <span class="value price">¥{{ service.price }}/{{ service.unit }}</span>
              </div>
              <div class="detail-item">
                <span class="label">服务区域：</span>
                <span class="value">{{ service.serviceArea }}</span>
              </div>
              <div class="detail-item">
                <span class="label">预计时长：</span>
                <span class="value">{{ service.duration }}小时</span>
              </div>
            </div>
            
            <div class="service-stats">
              <div class="stat-item">
                <span class="stat-number">{{ service.orderCount || 0 }}</span>
                <span class="stat-text">订单</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ service.rating || 5.0 }}</span>
                <span class="stat-text">评分</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">¥{{ service.revenue || 0 }}</span>
                <span class="stat-text">收入</span>
              </div>
            </div>
          </div>
          
          <div class="service-actions">
            <el-button size="small" @click="viewServiceDetail(service)" type="info">详情</el-button>
            <el-button size="small" @click="editService(service)">编辑</el-button>
            <el-button
              v-if="service.status === SERVICE_STATUS.ACTIVE"
              size="small"
              type="primary"
              @click="managePromotion(service)"
            >
              推广
            </el-button>
            <el-button
              size="small"
              :type="getStatusButtonType(service.status)"
              @click="toggleServiceStatus(service)"
            >
              {{ getStatusButtonText(service.status) }}
            </el-button>
            <el-button
              v-if="service.status === SERVICE_STATUS.DRAFT"
              size="small"
              type="success"
              @click="submitServiceForReview(service)"
            >
              提交审核
            </el-button>
            <el-button size="small" type="danger" @click="deleteService(service)">删除</el-button>
          </div>
        </div>
        
        <!-- 添加服务卡片 -->
        <div class="service-card add-service-card" @click="showServiceDialog">
          <div class="add-service-content">
            <el-icon class="add-icon"><Plus /></el-icon>
            <div class="add-text">发布新服务</div>
            <div class="add-desc">让更多客户找到您的服务</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 发布/编辑服务对话框 -->
    <el-dialog
      v-model="serviceDialogVisible"
      :title="editingService ? '编辑服务' : '发布新服务'"
      width="600px"
      @close="resetServiceForm"
    >
      <el-form
        ref="serviceFormRef"
        :model="serviceForm"
        :rules="serviceRules"
        label-width="100px"
      >
        <el-form-item label="服务类型" prop="type">
          <el-select v-model="serviceForm.type" placeholder="请选择服务类型" style="width: 100%;" @change="handleServiceTypeChange">
            <el-option
              v-for="(text, type) in SERVICE_TYPE_TEXT"
              :key="type"
              :label="`${text} (押金: ¥${DEPOSIT_CONFIG[type]})`"
              :value="type"
            />
          </el-select>
          <div v-if="serviceForm.type && !depositPaid[serviceForm.type]" class="deposit-warning">
            <el-alert
              :title="`需要支付 ¥${DEPOSIT_CONFIG[serviceForm.type]} 押金才能发布此类型服务`"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <div style="margin-top: 10px;">
                  <el-button type="primary" size="small" @click="handlePayDeposit">
                    立即支付押金
                  </el-button>
                </div>
              </template>
            </el-alert>
          </div>
        </el-form-item>

        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name" placeholder="请输入服务名称" maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            placeholder="请详细描述您的服务内容、特色和优势"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="服务价格" prop="price">
              <el-input-number
                v-model="serviceForm.price"
                :min="0"
                :precision="2"
                controls-position="right"
                style="width: 100%;"
                placeholder="0.00"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计价单位" prop="unit">
              <el-select v-model="serviceForm.unit" placeholder="请选择计价单位" style="width: 100%;">
                <el-option
                  v-for="unit in PRICING_UNITS"
                  :key="unit.value"
                  :label="unit.label"
                  :value="unit.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大服务距离" prop="maxDistance">
              <el-input-number
                v-model="serviceForm.maxDistance"
                :min="1"
                :max="50"
                controls-position="right"
                style="width: 100%;"
                placeholder="公里"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <ServiceAreaSelector
          v-model="serviceForm.serviceArea"
          @change="handleServiceAreaChange"
        />

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计时长" prop="duration">
              <el-input-number
                v-model="serviceForm.duration"
                :min="0.5"
                :max="168"
                :step="0.5"
                controls-position="right"
                style="width: 100%;"
                placeholder="小时"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否支持预约" prop="supportBooking">
              <el-radio-group v-model="serviceForm.supportBooking">
                <el-radio :label="true">支持预约</el-radio>
                <el-radio :label="false">不支持预约</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否免费上门取货" prop="freePickup">
              <el-radio-group v-model="serviceForm.freePickup">
                <el-radio :label="true">免费上门取货</el-radio>
                <el-radio :label="false">不提供上门取货</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否麻烦配送" prop="troublesomeDelivery">
              <el-radio-group v-model="serviceForm.troublesomeDelivery">
                <el-radio :label="false">正常配送</el-radio>
                <el-radio :label="true">麻烦配送</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="服务图片" prop="images">
          <div class="upload-section">
            <el-upload
              v-model:file-list="serviceForm.images"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="10"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tips">
              <p>• 请上传4-10张服务相关图片</p>
              <p>• 支持 JPG、PNG 格式，单张不超过 5MB</p>
              <p>• 建议上传服务现场、设备、效果对比等图片</p>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="serviceDialogVisible = false">取消</el-button>
        <el-button @click="saveDraft" :loading="draftSaving">
          保存草稿
        </el-button>
        <el-button type="primary" :loading="serviceSubmitting" @click="submitService">
          {{ editingService ? '保存修改' : '提交审核' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 推广管理对话框 -->
    <el-dialog
      v-model="promotionDialogVisible"
      title="推广管理"
      width="600px"
    >
      <div v-if="currentPromotionService" class="promotion-content">
        <div class="service-info">
          <h3>{{ currentPromotionService.name }}</h3>
          <p>{{ currentPromotionService.description }}</p>
        </div>

        <el-divider />

        <div class="promotion-stats">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ promotionData.views || 0 }}</div>
                <div class="stat-label">曝光次数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ promotionData.clicks || 0 }}</div>
                <div class="stat-label">点击次数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ promotionData.orders || 0 }}</div>
                <div class="stat-label">转化订单</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider />

        <div class="promotion-controls">
          <el-form label-width="100px">
            <el-form-item label="推广状态">
              <el-switch
                v-model="promotionData.enabled"
                active-text="开启推广"
                inactive-text="关闭推广"
                @change="handlePromotionToggle"
              />
            </el-form-item>

            <el-form-item label="推广链接" v-if="promotionData.enabled">
              <el-input
                :value="promotionData.link"
                readonly
                placeholder="推广链接将在开启推广后生成"
              >
                <template #append>
                  <el-button @click="copyPromotionLink">复制</el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="推广说明">
              <el-alert
                title="推广说明"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <ul style="margin: 0; padding-left: 20px;">
                    <li>新服务将获得3小时密集曝光</li>
                    <li>系统根据用户反馈自动调整曝光</li>
                    <li>高级推广需要后台审批</li>
                    <li>推广效果基于订单量和咨询量</li>
                  </ul>
                </template>
              </el-alert>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <el-button @click="promotionDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshPromotionData">刷新数据</el-button>
      </template>
    </el-dialog>

    <!-- 模板选择对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="选择服务模板"
      width="800px"
    >
      <div class="template-grid">
        <div
          v-for="template in serviceTemplates"
          :key="template.id"
          class="template-card"
          @click="selectTemplate(template)"
        >
          <div class="template-header">
            <div class="template-icon" :class="getServiceIconClass(template.type)">
              <el-icon><component :is="getServiceIcon(template.type)" /></el-icon>
            </div>
            <div class="template-info">
              <h4>{{ template.name }}</h4>
              <p>{{ template.description }}</p>
            </div>
          </div>
          <div class="template-details">
            <div class="detail-row">
              <span>价格：¥{{ template.price }}/{{ template.unit }}</span>
            </div>
            <div class="detail-row">
              <span>时长：{{ template.duration }}小时</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="templateDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 复制服务对话框 -->
    <el-dialog
      v-model="copyDialogVisible"
      title="选择要复制的服务"
      width="600px"
    >
      <el-table :data="publishedServices" @row-click="selectServiceToCopy">
        <el-table-column prop="name" label="服务名称" />
        <el-table-column prop="type" label="服务类型">
          <template #default="{ row }">
            {{ SERVICE_TYPE_TEXT[row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格">
          <template #default="{ row }">
            ¥{{ row.price }}/{{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="SERVICE_STATUS_COLOR[row.status]">
              {{ SERVICE_STATUS_TEXT[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="copyDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 服务分析对话框 -->
    <el-dialog
      v-model="analysisDialogVisible"
      :title="analysisTitle"
      width="900px"
      top="5vh"
    >
      <div class="analysis-content">
        <!-- 时间范围选择 -->
        <div class="analysis-header">
          <el-radio-group v-model="analysisTimeRange" @change="loadAnalysisData">
            <el-radio-button label="7d">近7天</el-radio-button>
            <el-radio-button label="30d">近30天</el-radio-button>
            <el-radio-button label="90d">近90天</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
          <el-date-picker
            v-if="analysisTimeRange === 'custom'"
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="loadAnalysisData"
            style="margin-left: 10px;"
          />
        </div>

        <!-- 分析图表 -->
        <div class="analysis-charts">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <span>{{ analysisType === 'order' ? '订单趋势' : '收入趋势' }}</span>
                </template>
                <div class="chart-container" ref="trendChartRef"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card">
                <template #header>
                  <span>服务类型分布</span>
                </template>
                <div class="chart-container" ref="pieChartRef"></div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <el-card class="chart-card">
                <template #header>
                  <span>服务排行榜</span>
                </template>
                <el-table :data="serviceRanking" style="width: 100%">
                  <el-table-column prop="rank" label="排名" width="80" align="center">
                    <template #default="{ row }">
                      <el-tag
                        :type="row.rank <= 3 ? 'warning' : 'info'"
                        size="small"
                      >
                        #{{ row.rank }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="服务名称" />
                  <el-table-column prop="type" label="类型">
                    <template #default="{ row }">
                      {{ SERVICE_TYPE_TEXT[row.type] }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="orders" label="订单数" width="100" align="center" />
                  <el-table-column prop="revenue" label="收入" width="120" align="center">
                    <template #default="{ row }">
                      ¥{{ formatMoney(row.revenue) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="rating" label="评分" width="100" align="center">
                    <template #default="{ row }">
                      <el-rate
                        v-model="row.rating"
                        disabled
                        show-score
                        text-color="#ff9900"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" align="center">
                    <template #default="{ row }">
                      <el-button size="small" type="primary" @click="viewServiceDetail(row)">
                        查看详情
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 分析洞察 -->
        <div class="analysis-insights">
          <el-card>
            <template #header>
              <span>数据洞察</span>
            </template>
            <div class="insights-grid">
              <div class="insight-item" v-for="insight in analysisInsights" :key="insight.id">
                <div class="insight-icon" :class="insight.type">
                  <el-icon><component :is="insight.icon" /></el-icon>
                </div>
                <div class="insight-content">
                  <h4>{{ insight.title }}</h4>
                  <p>{{ insight.description }}</p>
                  <div class="insight-action" v-if="insight.action">
                    <el-button size="small" type="primary" @click="handleInsightAction(insight)">
                      {{ insight.actionText }}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <template #footer>
        <el-button @click="analysisDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="exportAnalysisReport">导出报告</el-button>
      </template>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchActionDialogVisible"
      title="批量操作"
      width="500px"
    >
      <div class="batch-actions-content">
        <div class="selected-info">
          <el-alert
            :title="`已选择 ${selectedServices.length} 个服务`"
            type="info"
            :closable="false"
            show-icon
          />
        </div>

        <div class="action-buttons">
          <el-button
            type="success"
            size="large"
            @click="batchActivateServices"
            :disabled="selectedServices.length === 0"
          >
            <el-icon><Check /></el-icon>
            批量上架
          </el-button>

          <el-button
            type="warning"
            size="large"
            @click="batchDeactivateServices"
            :disabled="selectedServices.length === 0"
          >
            <el-icon><Close /></el-icon>
            批量下架
          </el-button>

          <el-button
            type="danger"
            size="large"
            @click="batchDeleteServices"
            :disabled="selectedServices.length === 0"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>

        <div class="batch-tips">
          <el-alert
            title="操作提示"
            type="warning"
            :closable="false"
          >
            <template #default>
              <ul style="margin: 0; padding-left: 20px;">
                <li>批量上架：将选中的服务设置为上架状态</li>
                <li>批量下架：将选中的服务设置为下架状态</li>
                <li>批量删除：永久删除选中的服务，无法恢复</li>
              </ul>
            </template>
          </el-alert>
        </div>
      </div>

      <template #footer>
        <el-button @click="batchActionDialogVisible = false">取消</el-button>
        <el-button @click="selectedServices = []">清空选择</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="800px">
      <div class="image-preview-container">
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
      </div>
    </el-dialog>

    <!-- 服务详情查看对话框 -->
    <el-dialog
      v-model="serviceDetailDialogVisible"
      title="服务详情"
      width="900px"
      top="5vh"
    >
      <div v-if="currentViewService" class="service-detail-content">
        <!-- 服务基本信息 -->
        <el-row :gutter="20">
          <el-col :span="16">
            <el-card class="detail-card">
              <template #header>
                <span>基本信息</span>
              </template>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="服务名称">
                  {{ currentViewService.name }}
                </el-descriptions-item>
                <el-descriptions-item label="服务类型">
                  {{ SERVICE_TYPE_TEXT[currentViewService.type] }}
                </el-descriptions-item>
                <el-descriptions-item label="服务价格">
                  ¥{{ currentViewService.price }}/{{ currentViewService.unit }}
                </el-descriptions-item>
                <el-descriptions-item label="服务状态">
                  <el-tag :type="SERVICE_STATUS_COLOR[currentViewService.status]">
                    {{ SERVICE_STATUS_TEXT[currentViewService.status] }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="服务区域">
                  {{ currentViewService.serviceArea }}
                </el-descriptions-item>
                <el-descriptions-item label="最大距离">
                  {{ currentViewService.maxDistance }}公里
                </el-descriptions-item>
                <el-descriptions-item label="预计时长">
                  {{ currentViewService.duration }}小时
                </el-descriptions-item>
                <el-descriptions-item label="支持预约">
                  <el-tag :type="currentViewService.supportBooking ? 'success' : 'info'">
                    {{ currentViewService.supportBooking ? '支持' : '不支持' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="免费取货">
                  <el-tag :type="currentViewService.freePickup ? 'success' : 'info'">
                    {{ currentViewService.freePickup ? '免费' : '收费' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="配送难度">
                  <el-tag :type="currentViewService.troublesomeDelivery ? 'warning' : 'success'">
                    {{ currentViewService.troublesomeDelivery ? '麻烦配送' : '正常配送' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="服务描述" :span="2">
                  {{ currentViewService.description }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="detail-card">
              <template #header>
                <span>运营数据</span>
              </template>
              <div class="operation-stats">
                <div class="stat-row">
                  <span class="stat-label">总订单数：</span>
                  <span class="stat-value">{{ currentViewService.orderCount || 0 }}</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">服务评分：</span>
                  <span class="stat-value">
                    <el-rate
                      :model-value="currentViewService.rating || 5.0"
                      disabled
                      show-score
                      text-color="#ff9900"
                    />
                  </span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">总收入：</span>
                  <span class="stat-value revenue">¥{{ formatMoney(currentViewService.revenue || 0) }}</span>
                </div>
                <div class="stat-row">
                  <span class="stat-label">创建时间：</span>
                  <span class="stat-value">{{ formatDateTime(currentViewService.createTime) }}</span>
                </div>
                <div class="stat-row" v-if="currentViewService.updateTime">
                  <span class="stat-label">更新时间：</span>
                  <span class="stat-value">{{ formatDateTime(currentViewService.updateTime) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 服务图片 -->
        <el-card class="detail-card" style="margin-top: 20px;" v-if="currentViewService.images && currentViewService.images.length > 0">
          <template #header>
            <span>服务图片</span>
          </template>
          <div class="service-images">
            <div
              v-for="(image, index) in currentViewService.images"
              :key="index"
              class="image-item"
              @click="previewImage(image.url)"
            >
              <img :src="image.url" :alt="`服务图片${index + 1}`" />
            </div>
          </div>
        </el-card>

        <!-- 最近订单 -->
        <el-card class="detail-card" style="margin-top: 20px;">
          <template #header>
            <span>最近订单</span>
            <el-button type="primary" size="small" style="float: right;" @click="viewAllOrders">
              查看全部
            </el-button>
          </template>
          <el-table :data="recentOrders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="150" />
            <el-table-column prop="customerName" label="客户" width="100" />
            <el-table-column prop="amount" label="金额" width="100">
              <template #default="{ row }">
                ¥{{ row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag size="small" :type="getOrderStatusType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间">
              <template #default="{ row }">
                {{ formatDateTime(row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="serviceDetailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="editCurrentViewService">编辑服务</el-button>
        <el-button
          v-if="currentViewService && currentViewService.status === SERVICE_STATUS.ACTIVE"
          type="success"
          @click="manageCurrentServicePromotion"
        >
          推广管理
        </el-button>
      </template>
    </el-dialog>

    <!-- 高级筛选对话框 -->
    <el-dialog
      v-model="advancedFilterDialogVisible"
      title="高级筛选"
      width="600px"
    >
      <el-form :model="advancedFilters" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格范围">
              <el-slider
                v-model="advancedFilters.priceRange"
                range
                :min="0"
                :max="500"
                :step="5"
                show-stops
                show-input
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评分范围">
              <el-slider
                v-model="advancedFilters.ratingRange"
                range
                :min="0"
                :max="5"
                :step="0.1"
                show-input
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单数量">
              <el-input-number
                v-model="advancedFilters.minOrders"
                :min="0"
                placeholder="最少订单数"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务时长">
              <el-select v-model="advancedFilters.durationRange" placeholder="选择时长范围" style="width: 100%;">
                <el-option label="全部" value="" />
                <el-option label="1小时内" value="0-1" />
                <el-option label="1-6小时" value="1-6" />
                <el-option label="6-24小时" value="6-24" />
                <el-option label="24小时以上" value="24+" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支持预约">
              <el-radio-group v-model="advancedFilters.supportBooking">
                <el-radio :label="null">全部</el-radio>
                <el-radio :label="true">支持</el-radio>
                <el-radio :label="false">不支持</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="免费取货">
              <el-radio-group v-model="advancedFilters.freePickup">
                <el-radio :label="null">全部</el-radio>
                <el-radio :label="true">免费</el-radio>
                <el-radio :label="false">收费</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="advancedFilters.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="服务区域">
          <el-input
            v-model="advancedFilters.serviceArea"
            placeholder="输入服务区域关键词"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="resetAdvancedFilters">重置</el-button>
        <el-button @click="advancedFilterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="applyAdvancedFilters">应用筛选</el-button>
      </template>
    </el-dialog>

    <!-- 服务洞察对话框 -->
    <el-dialog
      v-model="insightsDialogVisible"
      title="服务洞察"
      width="900px"
      top="5vh"
    >
      <div v-if="insightsData" class="insights-content">
        <!-- 概览指标 -->
        <el-row :gutter="20" class="insights-overview">
          <el-col :span="6">
            <el-card class="insight-card">
              <div class="insight-metric">
                <div class="metric-value">{{ insightsData.totalViews || 0 }}</div>
                <div class="metric-label">总浏览量</div>
                <div class="metric-trend" :class="insightsData.viewsTrend > 0 ? 'trend-up' : 'trend-down'">
                  {{ insightsData.viewsTrend > 0 ? '+' : '' }}{{ insightsData.viewsTrend }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="insight-card">
              <div class="insight-metric">
                <div class="metric-value">{{ insightsData.conversionRate || 0 }}%</div>
                <div class="metric-label">转化率</div>
                <div class="metric-trend" :class="insightsData.conversionTrend > 0 ? 'trend-up' : 'trend-down'">
                  {{ insightsData.conversionTrend > 0 ? '+' : '' }}{{ insightsData.conversionTrend }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="insight-card">
              <div class="insight-metric">
                <div class="metric-value">¥{{ formatMoney(insightsData.avgOrderValue || 0) }}</div>
                <div class="metric-label">平均订单价值</div>
                <div class="metric-trend" :class="insightsData.aovTrend > 0 ? 'trend-up' : 'trend-down'">
                  {{ insightsData.aovTrend > 0 ? '+' : '' }}{{ insightsData.aovTrend }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="insight-card">
              <div class="insight-metric">
                <div class="metric-value">{{ insightsData.customerSatisfaction || 0 }}%</div>
                <div class="metric-label">客户满意度</div>
                <div class="metric-trend" :class="insightsData.satisfactionTrend > 0 ? 'trend-up' : 'trend-down'">
                  {{ insightsData.satisfactionTrend > 0 ? '+' : '' }}{{ insightsData.satisfactionTrend }}%
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 服务表现排行 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card class="insight-card">
              <template #header>
                <span>热门服务排行</span>
              </template>
              <div class="service-ranking">
                <div
                  v-for="(service, index) in insightsData.topServices"
                  :key="service.id"
                  class="ranking-item"
                >
                  <div class="rank-number" :class="`rank-${index + 1}`">{{ index + 1 }}</div>
                  <div class="service-info">
                    <div class="service-name">{{ service.name }}</div>
                    <div class="service-stats">
                      <span>{{ service.orderCount }}单</span>
                      <span>¥{{ formatMoney(service.revenue) }}</span>
                    </div>
                  </div>
                  <div class="service-trend">
                    <el-icon :class="service.trend > 0 ? 'trend-up' : 'trend-down'">
                      <component :is="service.trend > 0 ? 'TrendCharts' : 'Bottom'" />
                    </el-icon>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="insight-card">
              <template #header>
                <span>客户画像</span>
              </template>
              <div class="customer-profile">
                <div class="profile-item">
                  <span class="label">主要年龄段：</span>
                  <span class="value">{{ insightsData.customerProfile?.ageGroup || '暂无数据' }}</span>
                </div>
                <div class="profile-item">
                  <span class="label">性别分布：</span>
                  <span class="value">{{ insightsData.customerProfile?.genderRatio || '暂无数据' }}</span>
                </div>
                <div class="profile-item">
                  <span class="label">消费偏好：</span>
                  <span class="value">{{ insightsData.customerProfile?.preference || '暂无数据' }}</span>
                </div>
                <div class="profile-item">
                  <span class="label">活跃时段：</span>
                  <span class="value">{{ insightsData.customerProfile?.activeTime || '暂无数据' }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 优化建议 -->
        <el-card class="insight-card" style="margin-top: 20px;">
          <template #header>
            <span>优化建议</span>
          </template>
          <div class="optimization-suggestions">
            <div
              v-for="(suggestion, index) in insightsData.suggestions"
              :key="index"
              class="suggestion-item"
            >
              <div class="suggestion-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="suggestion-content">
                <div class="suggestion-title">{{ suggestion.title }}</div>
                <div class="suggestion-desc">{{ suggestion.description }}</div>
                <div class="suggestion-action">
                  <el-button size="small" type="primary" @click="applySuggestion(suggestion)">
                    {{ suggestion.actionText }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="insightsDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="exportInsightsReport">导出报告</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Star,
  Timer,
  List,
  Wallet,
  User,
  Car,
  Home,
  Tools,
  ArrowDown,
  Check,
  Close,
  Delete,
  Warning,
  TrendCharts,
  Bottom,
  Search,
  Filter,
  Refresh,
  Download
} from '@element-plus/icons-vue'
import {
  getServicesList,
  getServiceStats,
  createService,
  updateService,
  deleteService,
  toggleServiceStatus,
  saveDraft,
  uploadServiceImage,
  checkDepositStatus,
  payDeposit,
  getServiceAnalysis,
  getServiceRanking,
  getServiceOrders,
  batchUpdateServices,
  exportServicesData,
  getServiceTemplates,
  copyService,
  getPromotionData,
  togglePromotion,
  getPromotionStats,
  searchServices,
  getDepositStatusList,
  getServiceInsights,
  getServicePerformanceReport,
  getCompetitorAnalysis,
  getServiceOptimizationSuggestions,
  SERVICE_STATUS,
  SERVICE_STATUS_TEXT,
  SERVICE_STATUS_COLOR,
  SERVICE_TYPES,
  SERVICE_TYPE_TEXT,
  DEPOSIT_CONFIG,
  PRICING_UNITS
} from '@/api/services'
import ServiceAreaSelector from '@/components/ServiceAreaSelector.vue'

// 响应式数据
const activeTab = ref('published')
const filterStatus = ref('')
const filterType = ref('')
const serviceDialogVisible = ref(false)
const serviceSubmitting = ref(false)
const draftSaving = ref(false)
const editingService = ref(null)
const serviceFormRef = ref(null)
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')
const loading = ref(false)

// 推广管理相关
const promotionDialogVisible = ref(false)
const currentPromotionService = ref(null)
const promotionData = reactive({
  enabled: false,
  link: '',
  views: 0,
  clicks: 0,
  orders: 0
})

// 模板相关
const templateDialogVisible = ref(false)
const copyDialogVisible = ref(false)

// 分析相关
const analysisDialogVisible = ref(false)
const analysisType = ref('order') // 'order' | 'revenue'
const analysisTitle = ref('')
const analysisTimeRange = ref('30d')
const customDateRange = ref([])
const trendChartRef = ref(null)
const pieChartRef = ref(null)

// 分析数据
const serviceRanking = ref([])
const analysisInsights = ref([])

// 批量操作相关
const selectedServices = ref([])
const batchActionDialogVisible = ref(false)

// 服务详情查看相关
const serviceDetailDialogVisible = ref(false)
const currentViewService = ref(null)
const recentOrders = ref([])

// 搜索和筛选相关
const searchKeyword = ref('')
const sortBy = ref('default')
const advancedFilterDialogVisible = ref(false)
const advancedFilters = reactive({
  priceRange: [0, 500],
  ratingRange: [0, 5],
  minOrders: null,
  durationRange: '',
  supportBooking: null,
  freePickup: null,
  createTimeRange: [],
  serviceArea: ''
})

// 服务洞察相关
const insightsDialogVisible = ref(false)
const insightsData = ref(null)

// 服务模板
const serviceTemplates = ref([])

// 押金状态管理
const depositPaid = reactive({
  [SERVICE_TYPES.LAUNDRY]: false,
  [SERVICE_TYPES.SHOES]: false,
  [SERVICE_TYPES.PET]: false,
  [SERVICE_TYPES.BAG]: false,
  [SERVICE_TYPES.BEDDING]: false,
  [SERVICE_TYPES.CAR]: false,
  [SERVICE_TYPES.HOME_CLEANING]: false,
  [SERVICE_TYPES.PLUMBING]: false
})

// 服务统计
const serviceStats = reactive({
  active: 0,
  inactive: 0,
  totalOrders: 0,
  totalRevenue: 0,
  activeTrend: 0,
  inactiveTrend: 0,
  ordersTrend: 0,
  revenueTrend: 0
})

// 加载服务统计数据
const loadServiceStats = async () => {
  try {
    const response = await getServiceStats()
    if (response.code === 200) {
      Object.assign(serviceStats, response.data)
    } else {
      throw new Error(response.message || '获取服务统计失败')
    }
  } catch (error) {
    console.error('获取服务统计失败:', error)
    ElMessage.error(error.message || '获取服务统计失败')
    // 重置为0
    Object.assign(serviceStats, {
      total: 0,
      active: 0,
      pending: 0,
      draft: 0,
      totalOrders: 0,
      totalRevenue: 0,
      ordersTrend: 0,
      revenueTrend: 0
    })
  }
}

// 服务表单
const serviceForm = reactive({
  type: '',
  name: '',
  description: '',
  price: 0,
  unit: '件',
  serviceArea: '',
  duration: 24,
  maxDistance: 10,
  supportBooking: true,
  freePickup: true,
  troublesomeDelivery: false,
  images: [],
  status: 'draft' // draft: 草稿, pending: 待审核, approved: 已通过, rejected: 已驳回
})

// 表单验证规则
const serviceRules = {
  type: [
    { required: true, message: '请选择服务类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 2, max: 30, message: '服务名称长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入服务描述', trigger: 'blur' },
    { min: 20, max: 500, message: '服务描述长度在 20 到 500 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入服务价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择计价单位', trigger: 'change' }
  ],
  serviceArea: [
    { required: true, message: '请输入服务区域', trigger: 'blur' },
    { min: 5, message: '请详细描述服务区域', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入预计时长', trigger: 'blur' },
    { type: 'number', min: 0.5, max: 168, message: '时长在 0.5 到 168 小时之间', trigger: 'blur' }
  ],
  maxDistance: [
    { required: true, message: '请输入最大服务距离', trigger: 'blur' },
    { type: 'number', min: 1, max: 50, message: '服务距离在 1 到 50 公里之间', trigger: 'blur' }
  ],
  images: [
    {
      validator: (rule, value, callback) => {
        if (value.length < 4) {
          callback(new Error('请至少上传4张服务图片'))
        } else if (value.length > 10) {
          callback(new Error('最多只能上传10张图片'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 服务列表
const services = ref([])

// 加载服务列表
const loadServicesList = async () => {
  try {
    loading.value = true

    const params = {
      page: 0,
      size: 100, // 获取所有服务
      keyword: searchKeyword.value,
      status: filterStatus.value,
      type: filterType.value,
      sortBy: sortBy.value
    }

    const response = await getServicesList(params)
    if (response.code === 200) {
      services.value = response.data.records || response.data || []
    } else {
      throw new Error(response.message || '获取服务列表失败')
    }
  } catch (error) {
    console.error('获取服务列表失败:', error)
    ElMessage.error(error.message || '获取服务列表失败')
    services.value = []
  } finally {
    loading.value = false
  }
}

// 加载押金状态
const loadDepositStatus = async () => {
  try {
    const response = await getDepositStatusList()
    if (response.code === 200) {
      Object.assign(depositPaid, response.data)
    } else {
      throw new Error(response.message || '获取押金状态失败')
    }
  } catch (error) {
    console.error('获取押金状态失败:', error)
    ElMessage.error(error.message || '获取押金状态失败')
  }
}

// 加载服务模板
const loadServiceTemplates = async () => {
  try {
    const response = await getServiceTemplates()
    if (response.code === 200) {
      serviceTemplates.value = response.data || []
    } else {
      throw new Error(response.message || '获取服务模板失败')
    }
  } catch (error) {
    console.error('获取服务模板失败:', error)
    ElMessage.error(error.message || '获取服务模板失败')
    serviceTemplates.value = []
  }
}

// 处理服务类型变化
const handleServiceTypeChange = (type) => {
  if (type && !depositPaid[type]) {
    ElMessage.warning(`发布${SERVICE_TYPE_TEXT[type]}服务需要先支付 ¥${DEPOSIT_CONFIG[type]} 押金`)
  }
}

// 处理服务区域变化
const handleServiceAreaChange = (areaData) => {
  console.log('服务区域变化:', areaData)
  // 可以在这里处理服务区域变化的逻辑
  // 比如根据区域类型调整价格、服务距离等
}

// 支付押金
const handlePayDeposit = async () => {
  if (!serviceForm.type) {
    ElMessage.warning('请先选择服务类型')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认支付 ¥${DEPOSIT_CONFIG[serviceForm.type]} 押金？\n押金将在店铺关闭且无纠纷时自动退还`,
      '支付押金',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await payDeposit(serviceForm.type, DEPOSIT_CONFIG[serviceForm.type])
    if (response.code === 200) {
      depositPaid[serviceForm.type] = true
      ElMessage.success('押金支付成功！现在可以发布此类型服务了')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付押金失败:', error)
      ElMessage.error('支付押金失败')
    }
  }
}

// 计算属性 - 按状态分类服务
const publishedServices = computed(() => {
  return services.value.filter(service =>
    [SERVICE_STATUS.ACTIVE, SERVICE_STATUS.INACTIVE, SERVICE_STATUS.APPROVED].includes(service.status)
  )
})

const draftServices = computed(() => {
  return services.value.filter(service => service.status === SERVICE_STATUS.DRAFT)
})

const pendingServices = computed(() => {
  return services.value.filter(service => service.status === SERVICE_STATUS.PENDING)
})

const rejectedServices = computed(() => {
  return services.value.filter(service => service.status === SERVICE_STATUS.REJECTED)
})

// 当前标签页的服务列表
const currentTabServices = computed(() => {
  let baseServices = []

  switch (activeTab.value) {
    case 'published':
      baseServices = publishedServices.value
      break
    case 'drafts':
      baseServices = draftServices.value
      break
    case 'pending':
      baseServices = pendingServices.value
      break
    case 'rejected':
      baseServices = rejectedServices.value
      break
    default:
      baseServices = services.value
  }

  // 应用基础筛选条件
  let filtered = baseServices.filter(service => {
    const statusMatch = !filterStatus.value || service.status === filterStatus.value
    const typeMatch = !filterType.value || service.type === filterType.value

    // 搜索关键词匹配
    const keywordMatch = !searchKeyword.value ||
      service.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      service.description.toLowerCase().includes(searchKeyword.value.toLowerCase())

    return statusMatch && typeMatch && keywordMatch
  })

  // 应用高级筛选
  if (hasAdvancedFilters.value) {
    filtered = filtered.filter(service => {
      // 价格范围
      if (service.price < advancedFilters.priceRange[0] || service.price > advancedFilters.priceRange[1]) {
        return false
      }

      // 评分范围
      const rating = service.rating || 5.0
      if (rating < advancedFilters.ratingRange[0] || rating > advancedFilters.ratingRange[1]) {
        return false
      }

      // 最少订单数
      if (advancedFilters.minOrders && (service.orderCount || 0) < advancedFilters.minOrders) {
        return false
      }

      // 服务时长
      if (advancedFilters.durationRange) {
        const duration = service.duration || 0
        const [min, max] = advancedFilters.durationRange.split('-').map(v => v === '+' ? Infinity : Number(v))
        if (duration < min || (max !== Infinity && duration > max)) {
          return false
        }
      }

      // 支持预约
      if (advancedFilters.supportBooking !== null && service.supportBooking !== advancedFilters.supportBooking) {
        return false
      }

      // 免费取货
      if (advancedFilters.freePickup !== null && service.freePickup !== advancedFilters.freePickup) {
        return false
      }

      // 服务区域
      if (advancedFilters.serviceArea && !service.serviceArea.includes(advancedFilters.serviceArea)) {
        return false
      }

      return true
    })
  }

  return filtered
})

// 检查是否有高级筛选条件
const hasAdvancedFilters = computed(() => {
  return advancedFilters.priceRange[0] > 0 ||
         advancedFilters.priceRange[1] < 500 ||
         advancedFilters.ratingRange[0] > 0 ||
         advancedFilters.ratingRange[1] < 5 ||
         advancedFilters.minOrders ||
         advancedFilters.durationRange ||
         advancedFilters.supportBooking !== null ||
         advancedFilters.freePickup !== null ||
         advancedFilters.createTimeRange.length > 0 ||
         advancedFilters.serviceArea
})

// 兼容旧的 filteredServices，包含排序
const filteredServices = computed(() => {
  let result = [...currentTabServices.value]

  // 应用排序
  switch (sortBy.value) {
    case 'price-asc':
      result.sort((a, b) => (a.price || 0) - (b.price || 0))
      break
    case 'price-desc':
      result.sort((a, b) => (b.price || 0) - (a.price || 0))
      break
    case 'rating-desc':
      result.sort((a, b) => (b.rating || 0) - (a.rating || 0))
      break
    case 'orders-desc':
      result.sort((a, b) => (b.orderCount || 0) - (a.orderCount || 0))
      break
    case 'revenue-desc':
      result.sort((a, b) => (b.revenue || 0) - (a.revenue || 0))
      break
    case 'create-time':
      result.sort((a, b) => new Date(b.createTime || 0) - new Date(a.createTime || 0))
      break
    default:
      // 默认排序：已上架的在前，然后按创建时间降序
      result.sort((a, b) => {
        if (a.status === SERVICE_STATUS.ACTIVE && b.status !== SERVICE_STATUS.ACTIVE) return -1
        if (b.status === SERVICE_STATUS.ACTIVE && a.status !== SERVICE_STATUS.ACTIVE) return 1
        return new Date(b.createTime || 0) - new Date(a.createTime || 0)
      })
  }

  return result
})

// 方法
const getServiceIcon = (type) => {
  const iconMap = {
    'laundry': 'User',
    'shoes': 'Star',
    'pet': 'Timer',
    'bag': 'List',
    'bedding': 'Star',
    'car': 'Star',
    'home_cleaning': 'Tools',
    'plumbing': 'Tools'
  }
  return iconMap[type] || 'Star'
}

const getServiceIconClass = (type) => {
  const classMap = {
    'laundry': 'icon-laundry',
    'shoes': 'icon-shoes',
    'pet': 'icon-pet',
    'bag': 'icon-bag',
    'bedding': 'icon-bedding',
    'car': 'icon-car',
    'home_cleaning': 'icon-home',
    'plumbing': 'icon-plumbing'
  }
  return classMap[type] || 'icon-default'
}

// 标签页切换
const handleTabChange = (tabName) => {
  activeTab.value = tabName
  // 清空筛选条件
  filterStatus.value = ''
  filterType.value = ''
}

// 处理创建服务命令
const handleCreateService = async (command) => {
  switch (command) {
    case 'blank':
      showServiceDialog()
      break
    case 'template':
      await loadServiceTemplates()
      templateDialogVisible.value = true
      break
    case 'copy':
      copyDialogVisible.value = true
      break
  }
}

const showServiceDialog = () => {
  editingService.value = null
  resetServiceForm()
  serviceDialogVisible.value = true
}

// 选择模板
const selectTemplate = (template) => {
  // 填充表单数据
  Object.assign(serviceForm, {
    type: template.type,
    name: template.name,
    description: template.description,
    price: template.price,
    unit: template.unit,
    serviceArea: template.serviceArea,
    duration: template.duration,
    maxDistance: template.maxDistance,
    supportBooking: template.supportBooking,
    freePickup: template.freePickup,
    troublesomeDelivery: template.troublesomeDelivery,
    images: []
  })

  templateDialogVisible.value = false
  serviceDialogVisible.value = true
  ElMessage.success('模板已应用，请完善服务信息')
}

// 选择要复制的服务
const selectServiceToCopy = (service) => {
  // 复制服务数据，但重置一些字段
  Object.assign(serviceForm, {
    type: service.type,
    name: `${service.name} - 副本`,
    description: service.description,
    price: service.price,
    unit: service.unit,
    serviceArea: service.serviceArea,
    duration: service.duration,
    maxDistance: service.maxDistance,
    supportBooking: service.supportBooking,
    freePickup: service.freePickup,
    troublesomeDelivery: service.troublesomeDelivery,
    images: []
  })

  copyDialogVisible.value = false
  serviceDialogVisible.value = true
  ElMessage.success('服务已复制，请修改相关信息')
}

const resetServiceForm = () => {
  if (serviceFormRef.value) {
    serviceFormRef.value.resetFields()
  }
  Object.assign(serviceForm, {
    type: '',
    name: '',
    description: '',
    price: 0,
    unit: '件',
    serviceArea: '',
    duration: 24,
    maxDistance: 10,
    supportBooking: true,
    freePickup: true,
    troublesomeDelivery: false,
    images: [],
    status: 'draft'
  })
}

// 图片上传相关方法
const handlePictureCardPreview = (file) => {
  previewImageUrl.value = file.url
  previewDialogVisible.value = true
}

const handleRemove = (file, fileList) => {
  serviceForm.images = fileList
}

const beforeUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 保存草稿
const saveDraftLocal = async () => {
  try {
    draftSaving.value = true

    const draftData = {
      ...serviceForm,
      status: SERVICE_STATUS.DRAFT
    }

    let response
    if (editingService.value) {
      // 更新现有草稿
      response = await updateService(editingService.value.id, draftData)
    } else {
      // 创建新草稿 - 这里需要重命名避免冲突
      response = await createService(draftData)
    }

    if (response.code === 200) {
      ElMessage.success('草稿已保存')
      serviceDialogVisible.value = false
      resetServiceForm()
      await loadServicesList()
    } else {
      throw new Error(response.message || '保存草稿失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error(error.message || '保存草稿失败')

    // 如果API失败，使用本地存储
    if (import.meta.env.DEV) {
      console.warn('API失败，使用本地存储')
      const draftData = {
        ...serviceForm,
        id: editingService.value?.id || Date.now(),
        status: SERVICE_STATUS.DRAFT,
        updateTime: new Date().toISOString()
      }

      localStorage.setItem(`service_draft_${draftData.id}`, JSON.stringify(draftData))
      ElMessage.success('草稿已保存到本地')
      serviceDialogVisible.value = false
    }
  } finally {
    draftSaving.value = false
  }
}

// 为了避免命名冲突，创建一个别名
const saveDraft = saveDraftLocal

// 获取状态按钮类型
const getStatusButtonType = (status) => {
  switch (status) {
    case SERVICE_STATUS.ACTIVE:
      return 'warning'
    case SERVICE_STATUS.INACTIVE:
      return 'success'
    case SERVICE_STATUS.DRAFT:
      return 'info'
    default:
      return 'info'
  }
}

// 获取状态按钮文本
const getStatusButtonText = (status) => {
  switch (status) {
    case SERVICE_STATUS.ACTIVE:
      return '下架'
    case SERVICE_STATUS.INACTIVE:
      return '上架'
    case SERVICE_STATUS.DRAFT:
      return '编辑'
    case SERVICE_STATUS.PENDING:
      return '审核中'
    case SERVICE_STATUS.REJECTED:
      return '已驳回'
    default:
      return '操作'
  }
}

// 提交服务审核
const submitServiceForReview = async (service) => {
  try {
    await ElMessageBox.confirm('确认提交此服务进行审核？', '提交审核', {
      confirmButtonText: '确认提交',
      cancelButtonText: '取消',
      type: 'info'
    })

    const response = await updateService(service.id, {
      ...service,
      status: SERVICE_STATUS.PENDING
    })

    if (response.code === 200) {
      ElMessage.success('服务已提交审核')
      await loadServicesList()
    } else {
      throw new Error(response.message || '提交失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交审核失败:', error)
      ElMessage.error(error.message || '提交审核失败')
    }
  }
}

// 推广管理
const managePromotion = async (service) => {
  currentPromotionService.value = service
  promotionDialogVisible.value = true
  await loadPromotionData(service.id)
}

// 加载推广数据
const loadPromotionData = async (serviceId) => {
  try {
    const response = await getPromotionData(serviceId)
    if (response.code === 200) {
      Object.assign(promotionData, response.data)
    } else {
      throw new Error(response.message || '获取推广数据失败')
    }
  } catch (error) {
    console.error('获取推广数据失败:', error)
    ElMessage.error(error.message || '获取推广数据失败')
    // 重置推广数据
    Object.assign(promotionData, {
      enabled: false,
      link: '',
      views: 0,
      clicks: 0,
      orders: 0
    })
  }
}

// 切换推广状态
const handlePromotionToggle = async (enabled) => {
  try {
    const response = await togglePromotion(currentPromotionService.value.id, enabled)
    if (response.code === 200) {
      promotionData.enabled = enabled
      if (enabled) {
        promotionData.link = `https://example.com/service/${currentPromotionService.value.id}`
        ElMessage.success('推广已开启')
      } else {
        ElMessage.success('推广已关闭')
      }
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('切换推广状态失败:', error)
    ElMessage.error(error.message || '操作失败')
    // 回滚状态
    promotionData.enabled = !enabled
  }
}

// 复制推广链接
const copyPromotionLink = async () => {
  try {
    await navigator.clipboard.writeText(promotionData.link)
    ElMessage.success('推广链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 刷新推广数据
const refreshPromotionData = async () => {
  if (currentPromotionService.value) {
    await loadPromotionData(currentPromotionService.value.id)
    ElMessage.success('数据已刷新')
  }
}

// 格式化金额
const formatMoney = (amount) => {
  if (!amount) return '0'
  return Number(amount).toLocaleString()
}

// 按状态筛选
const filterByStatus = (status) => {
  activeTab.value = 'published'
  filterStatus.value = status
  ElMessage.info(`已筛选${SERVICE_STATUS_TEXT[status]}服务`)
}

// 显示订单分析
const showOrderAnalysis = () => {
  analysisType.value = 'order'
  analysisTitle.value = '订单数据分析'
  analysisDialogVisible.value = true
  loadAnalysisData()
}

// 显示收入分析
const showRevenueAnalysis = () => {
  analysisType.value = 'revenue'
  analysisTitle.value = '收入数据分析'
  analysisDialogVisible.value = true
  loadAnalysisData()
}

// 加载分析数据
const loadAnalysisData = async () => {
  try {
    // 获取服务排行榜
    const rankingResponse = await getServiceRanking({
      type: analysisType.value,
      timeRange: analysisTimeRange.value,
      customRange: analysisTimeRange.value === 'custom' ? customDateRange.value : null
    })

    if (rankingResponse.code === 200) {
      serviceRanking.value = rankingResponse.data || []
    }

    // 获取分析数据
    const analysisResponse = await getServiceAnalysis(
      analysisType.value,
      analysisTimeRange.value,
      analysisTimeRange.value === 'custom' ? customDateRange.value : null
    )

    if (analysisResponse.code === 200) {
      // 处理分析数据
      analysisInsights.value = analysisResponse.data.insights || []
    }
  } catch (error) {
    console.error('加载分析数据失败:', error)
    ElMessage.error(error.message || '加载分析数据失败')
    serviceRanking.value = []
    analysisInsights.value = []
  }
}



// 处理洞察建议
const handleInsightAction = (insight) => {
  switch (insight.action) {
    case 'promote':
      ElMessage.info('跳转到推广管理页面')
      break
    case 'optimize':
      ElMessage.info('跳转到服务优化页面')
      break
    case 'expand':
      showServiceDialog()
      break
  }
}

// 查看服务详情
const viewServiceDetail = (service) => {
  const targetService = services.value.find(s => s.id === service.id)
  if (targetService) {
    editService(targetService)
  }
}

// 导出分析报告
const exportAnalysisReport = () => {
  try {
    const reportData = {
      type: analysisType.value,
      timeRange: analysisTimeRange.value,
      stats: serviceStats,
      ranking: serviceRanking.value,
      insights: analysisInsights.value,
      exportTime: new Date().toISOString()
    }

    const dataStr = JSON.stringify(reportData, null, 2)
    const blob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `服务分析报告_${analysisType.value}_${new Date().toISOString().slice(0, 10)}.json`
    link.click()
    URL.revokeObjectURL(url)

    ElMessage.success('分析报告已导出')
  } catch (error) {
    console.error('导出报告失败:', error)
    ElMessage.error('导出报告失败')
  }
}

// 获取服务状态颜色
const getServiceStatusColor = (status) => {
  return SERVICE_STATUS_COLOR[status] || 'info'
}

// 切换服务选择
const toggleServiceSelection = (serviceId) => {
  const index = selectedServices.value.indexOf(serviceId)
  if (index > -1) {
    selectedServices.value.splice(index, 1)
  } else {
    selectedServices.value.push(serviceId)
  }
}

// 显示批量操作
const showBatchActions = () => {
  batchActionDialogVisible.value = true
}

// 批量上架
const batchActivateServices = async () => {
  try {
    await ElMessageBox.confirm(
      `确认批量上架 ${selectedServices.value.length} 个服务？`,
      '批量上架',
      {
        confirmButtonText: '确认上架',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await batchUpdateServices(selectedServices.value, 'activate')
    if (response.code === 200) {
      ElMessage.success(`成功上架 ${selectedServices.value.length} 个服务`)
      selectedServices.value = []
      await loadServicesList()
      await loadServiceStats()
    } else {
      throw new Error(response.message || '批量上架失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量上架失败:', error)
      ElMessage.error(error.message || '批量上架失败')
    }
  }
}

// 批量下架
const batchDeactivateServices = async () => {
  try {
    await ElMessageBox.confirm(
      `确认批量下架 ${selectedServices.value.length} 个服务？`,
      '批量下架',
      {
        confirmButtonText: '确认下架',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await batchUpdateServices(selectedServices.value, 'deactivate')
    if (response.code === 200) {
      ElMessage.success(`成功下架 ${selectedServices.value.length} 个服务`)
      selectedServices.value = []
      await loadServicesList()
      await loadServiceStats()
    } else {
      throw new Error(response.message || '批量下架失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量下架失败:', error)
      ElMessage.error(error.message || '批量下架失败')
    }
  }
}

// 批量删除
const batchDeleteServices = async () => {
  try {
    await ElMessageBox.confirm(
      `确认批量删除 ${selectedServices.value.length} 个服务？删除后无法恢复！`,
      '批量删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    const response = await batchUpdateServices(selectedServices.value, 'delete')
    if (response.code === 200) {
      ElMessage.success(`成功删除 ${selectedServices.value.length} 个服务`)
      selectedServices.value = []
      await loadServicesList()
      await loadServiceStats()
    } else {
      throw new Error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error(error.message || '批量删除失败')
    }
  }
}

const submitService = async () => {
  if (!serviceFormRef.value) return

  // 检查押金状态
  if (serviceForm.type && !depositPaid[serviceForm.type]) {
    ElMessage.error(`请先支付 ¥${DEPOSIT_CONFIG[serviceForm.type]} 押金才能发布此类型服务`)
    return
  }

  try {
    await serviceFormRef.value.validate()
    serviceSubmitting.value = true

    const serviceData = {
      ...serviceForm,
      status: SERVICE_STATUS.PENDING // 提交审核状态
    }

    let response
    if (editingService.value) {
      // 更新现有服务
      response = await updateService(editingService.value.id, serviceData)
    } else {
      // 创建新服务
      response = await createService(serviceData)
    }

    if (response.code === 200) {
      ElMessage.success(editingService.value ? '服务更新成功，等待审核' : '服务提交成功，等待审核')
      serviceDialogVisible.value = false
      resetServiceForm()
      await loadServicesList()
      await loadServiceStats()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交服务失败:', error)
    ElMessage.error(error.message || '提交服务失败')
  } finally {
    serviceSubmitting.value = false
  }
}

const editService = (service) => {
  editingService.value = service
  Object.assign(serviceForm, {
    type: service.type,
    name: service.name,
    description: service.description,
    price: service.price,
    unit: service.unit,
    serviceArea: service.serviceArea,
    duration: service.duration
  })
  serviceDialogVisible.value = true
}

const toggleServiceStatus = async (service) => {
  try {
    const isActive = service.status === SERVICE_STATUS.ACTIVE
    const action = isActive ? '下架' : '上架'
    const newStatus = isActive ? SERVICE_STATUS.INACTIVE : SERVICE_STATUS.ACTIVE

    await ElMessageBox.confirm(`确认${action}此服务？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await toggleServiceStatus(service.id, newStatus)
    if (response.code === 200) {
      service.status = newStatus
      ElMessage.success(`服务已${action}`)
      await loadServiceStats()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换服务状态失败:', error)
      ElMessage.error(error.message || '操作失败')
    } else {
      ElMessage.info('已取消操作')
    }
  }
}

const deleteService = async (service) => {
  try {
    await ElMessageBox.confirm('确认删除此服务？删除后无法恢复。', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    })

    const response = await deleteService(service.id)
    if (response.code === 200) {
      ElMessage.success('服务已删除')
      await loadServicesList()
      await loadServiceStats()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务失败:', error)
      ElMessage.error(error.message || '删除失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

// 查看服务详情
const viewServiceDetail = async (service) => {
  currentViewService.value = service
  serviceDetailDialogVisible.value = true
  await loadRecentOrders(service.id)
}

// 加载最近订单
const loadRecentOrders = async (serviceId) => {
  try {
    const response = await getServiceOrders(serviceId, { limit: 5 })
    if (response.code === 200) {
      recentOrders.value = response.data.records || response.data || []
    } else {
      throw new Error(response.message || '获取订单失败')
    }
  } catch (error) {
    console.error('加载最近订单失败:', error)
    ElMessage.error(error.message || '获取订单失败')
    recentOrders.value = []
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const statusMap = {
    '已完成': 'success',
    '进行中': 'primary',
    '已取消': 'danger',
    '待付款': 'warning'
  }
  return statusMap[status] || 'info'
}

// 编辑当前查看的服务
const editCurrentViewService = () => {
  serviceDetailDialogVisible.value = false
  editService(currentViewService.value)
}

// 管理当前服务推广
const manageCurrentServicePromotion = () => {
  serviceDetailDialogVisible.value = false
  managePromotion(currentViewService.value)
}

// 查看所有订单
const viewAllOrders = () => {
  ElMessage.info('跳转到订单管理页面')
  // 这里可以跳转到订单管理页面，并筛选当前服务的订单
  // router.push({ name: 'Orders', query: { serviceId: currentViewService.value.id } })
}

// 处理搜索
const handleSearch = debounce(() => {
  // 搜索逻辑已在计算属性中处理
}, 300)

// 显示高级筛选
const showAdvancedFilter = () => {
  advancedFilterDialogVisible.value = true
}

// 重置高级筛选
const resetAdvancedFilters = () => {
  Object.assign(advancedFilters, {
    priceRange: [0, 500],
    ratingRange: [0, 5],
    minOrders: null,
    durationRange: '',
    supportBooking: null,
    freePickup: null,
    createTimeRange: [],
    serviceArea: ''
  })
}

// 应用高级筛选
const applyAdvancedFilters = () => {
  advancedFilterDialogVisible.value = false
  ElMessage.success('筛选条件已应用')
}

// 全选相关计算属性
const selectAll = computed({
  get() {
    return selectedServices.value.length === filteredServices.value.length && filteredServices.value.length > 0
  },
  set(value) {
    if (value) {
      selectedServices.value = filteredServices.value.map(service => service.id)
    } else {
      selectedServices.value = []
    }
  }
})

const isIndeterminate = computed(() => {
  return selectedServices.value.length > 0 && selectedServices.value.length < filteredServices.value.length
})

// 处理全选
const handleSelectAll = (value) => {
  if (value) {
    selectedServices.value = filteredServices.value.map(service => service.id)
  } else {
    selectedServices.value = []
  }
}

// 刷新服务列表
const refreshServices = async () => {
  await loadServicesList()
  await loadServiceStats()
  ElMessage.success('服务列表已刷新')
}

// 导出服务
const exportServices = async () => {
  try {
    const response = await exportServicesData({
      filters: {
        status: filterStatus.value,
        type: filterType.value,
        keyword: searchKeyword.value
      }
    })

    // 如果后端返回文件流
    if (response instanceof Blob) {
      const url = URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url
      link.download = `服务列表_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.click()
      URL.revokeObjectURL(url)
      ElMessage.success('服务数据导出成功')
    } else {
      // 如果后端返回数据，前端生成CSV
      const exportData = filteredServices.value.map(service => ({
        '服务名称': service.name,
        '服务类型': SERVICE_TYPE_TEXT[service.type],
        '价格': `¥${service.price}/${service.unit}`,
        '状态': SERVICE_STATUS_TEXT[service.status],
        '服务区域': service.serviceArea,
        '预计时长': `${service.duration}小时`,
        '订单数量': service.orderCount || 0,
        '服务评分': service.rating || 5.0,
        '总收入': `¥${service.revenue || 0}`,
        '创建时间': formatDateTime(service.createTime)
      }))

      const headers = Object.keys(exportData[0])
      const csvContent = [
        headers.join(','),
        ...exportData.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
      ].join('\n')

      const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `服务列表_${new Date().toISOString().slice(0, 10)}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      ElMessage.success('服务数据导出成功')
    }
  } catch (error) {
    console.error('导出服务失败:', error)
    ElMessage.error(error.message || '导出服务失败')
  }
}

// 显示批量编辑
const showBulkEdit = () => {
  if (selectedServices.value.length === 0) {
    ElMessage.warning('请先选择要编辑的服务')
    return
  }
  batchActionDialogVisible.value = true
}

// 防抖函数
function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// API连接测试
const testApiConnections = async () => {
  const tests = [
    { name: '服务列表', fn: loadServicesList },
    { name: '服务统计', fn: loadServiceStats },
    { name: '押金状态', fn: loadDepositStatus }
  ]

  for (const test of tests) {
    try {
      await test.fn()
      console.log(`✅ ${test.name} API 连接正常`)
    } catch (error) {
      console.error(`❌ ${test.name} API 连接失败:`, error)
    }
  }
}

// 服务洞察相关方法
const showServiceInsights = async () => {
  try {
    insightsDialogVisible.value = true

    const response = await getServiceInsights({
      timeRange: '30d'
    })

    if (response.code === 200) {
      insightsData.value = response.data
    } else {
      throw new Error(response.message || '获取服务洞察失败')
    }
  } catch (error) {
    console.error('获取服务洞察失败:', error)
    ElMessage.error(error.message || '获取服务洞察失败')

    // 清空洞察数据，等待真实API
    insightsData.value = {
      totalViews: 0,
      viewsTrend: 0,
      conversionRate: 0,
      conversionTrend: 0,
      avgOrderValue: 0,
      aovTrend: 0,
      customerSatisfaction: 0,
      satisfactionTrend: 0,
      topServices: [],
      customerProfile: {
        ageGroup: '',
        genderRatio: '',
        preference: '',
        activeTime: ''
      },
      suggestions: []
    }
  }
}

const applySuggestion = (suggestion) => {
  ElMessage.info(`${suggestion.actionText}功能开发中...`)
}

const exportInsightsReport = async () => {
  try {
    // 生成洞察报告并导出
    ElMessage.success('洞察报告导出功能开发中...')
  } catch (error) {
    console.error('导出洞察报告失败:', error)
    ElMessage.error('导出洞察报告失败')
  }
}

// 页面初始化
onMounted(async () => {
  console.log('服务管理页面已加载')

  // 在开发环境下测试API连接
  if (import.meta.env.DEV) {
    await testApiConnections()
  }

  // 加载数据
  try {
    await Promise.all([
      loadServicesList(),
      loadServiceStats(),
      loadDepositStatus()
    ])
    console.log('✅ 所有数据加载完成')
  } catch (error) {
    console.error('❌ 数据加载失败:', error)
    ElMessage.error('页面数据加载失败，请刷新重试')
  }
})
</script>

<style scoped>
.services-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.active {
  background: linear-gradient(135deg, #10b981, #059669);
}

.stat-icon.inactive {
  background: linear-gradient(135deg, #6b7280, #4b5563);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

/* 服务列表 */
.services-list-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-filters {
  display: flex;
  gap: 12px;
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  padding: 10px 0;
}

.service-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  background: white;
  transition: all 0.3s ease;
  position: relative;
}

.service-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
  transform: translateY(-2px);
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.service-type-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.service-type-icon.icon-laundry {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.service-type-icon.icon-shoes {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.service-type-icon.icon-pet {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.service-type-icon.icon-bag {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.service-type-icon.icon-bedding {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.service-type-icon.icon-car {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
}

.service-type-icon.icon-home {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
}

.service-type-icon.icon-plumbing {
  background: linear-gradient(135deg, #89f7fe, #66a6ff);
}

.service-type-icon.icon-default {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.service-content h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #1f2937;
  font-weight: 600;
}

.service-description {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.service-details {
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-item .label {
  color: #6b7280;
}

.detail-item .value {
  color: #1f2937;
  font-weight: 500;
}

.detail-item .price {
  color: #059669;
  font-weight: 600;
  font-size: 16px;
}

.service-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-number {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 2px;
}

.stat-text {
  font-size: 12px;
  color: #6b7280;
}

.service-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 添加服务卡片 */
.add-service-card {
  border: 2px dashed #d1d5db;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 300px;
}

.add-service-card:hover {
  border-color: #3b82f6;
  background: #eff6ff;
  transform: translateY(-2px);
}

.add-service-content {
  text-align: center;
}

.add-icon {
  font-size: 48px;
  color: #9ca3af;
  margin-bottom: 12px;
}

.add-text {
  font-size: 16px;
  color: #374151;
  font-weight: 500;
  margin-bottom: 4px;
}

.add-desc {
  font-size: 14px;
  color: #6b7280;
}

/* 服务洞察样式 */
.insights-content {
  max-height: 70vh;
  overflow-y: auto;
}

.insights-overview {
  margin-bottom: 20px;
}

.insight-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.insight-card:last-child {
  margin-bottom: 0;
}

.insight-metric {
  text-align: center;
  padding: 20px;
}

.metric-value {
  font-size: 32px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.metric-trend {
  font-size: 12px;
  font-weight: 500;
}

.metric-trend.trend-up {
  color: #10b981;
}

.metric-trend.trend-down {
  color: #ef4444;
}

.service-ranking {
  padding: 10px 0;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.ranking-item:last-child {
  border-bottom: none;
}

.rank-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  margin-right: 12px;
}

.rank-number.rank-1 {
  background: #fbbf24;
}

.rank-number.rank-2 {
  background: #9ca3af;
}

.rank-number.rank-3 {
  background: #cd7c2f;
}

.rank-number:not(.rank-1):not(.rank-2):not(.rank-3) {
  background: #6b7280;
}

.service-info {
  flex: 1;
}

.service-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.service-stats {
  font-size: 12px;
  color: #6b7280;
}

.service-stats span {
  margin-right: 12px;
}

.service-trend {
  font-size: 18px;
}

.service-trend .trend-up {
  color: #10b981;
}

.service-trend .trend-down {
  color: #ef4444;
}

.customer-profile {
  padding: 10px 0;
}

.profile-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.profile-item:last-child {
  border-bottom: none;
}

.profile-item .label {
  color: #6b7280;
  font-size: 14px;
}

.profile-item .value {
  color: #1f2937;
  font-weight: 500;
  font-size: 14px;
}

.optimization-suggestions {
  padding: 10px 0;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  margin-bottom: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.suggestion-item:last-child {
  margin-bottom: 0;
}

.suggestion-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #fef3c7;
  color: #f59e0b;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.suggestion-content {
  flex: 1;
}

.suggestion-title {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.suggestion-desc {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 8px;
}

.suggestion-action {
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .services-management {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .services-grid {
    grid-template-columns: 1fr;
  }

  .header-filters {
    flex-direction: column;
    gap: 8px;
  }

  .insights-overview .el-col {
    margin-bottom: 16px;
  }

  .ranking-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .suggestion-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 12px 12px 0 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.stat-card .el-card__body) {
  padding: 0;
}

/* 押金警告样式 */
.deposit-warning {
  margin-top: 10px;
}

.deposit-warning .el-alert {
  border-radius: 8px;
}

/* 上传区域样式 */
.upload-section {
  width: 100%;
}

.upload-tips {
  margin-top: 10px;
  padding: 10px;
  background: #f8fafc;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

.upload-tips p {
  margin: 4px 0;
  font-size: 13px;
  color: #6b7280;
}

/* 标签页样式 */
.header-tabs {
  flex: 1;
}

.header-tabs .el-tabs__header {
  margin: 0;
}

.header-tabs .el-tabs__nav-wrap::after {
  display: none;
}

/* 推广管理样式 */
.promotion-content {
  padding: 10px 0;
}

.service-info h3 {
  margin: 0 0 8px 0;
  color: #1f2937;
}

.service-info p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.promotion-stats {
  margin: 20px 0;
}

.promotion-stats .stat-item {
  text-align: center;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.promotion-stats .stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.promotion-stats .stat-label {
  font-size: 14px;
  color: #6b7280;
}

.promotion-controls {
  margin-top: 20px;
}

/* 模板选择样式 */
.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.template-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.template-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
  transform: translateY(-1px);
}

.template-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.template-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 18px;
  color: white;
}

.template-info {
  flex: 1;
}

.template-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #1f2937;
}

.template-info p {
  margin: 0;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

.template-details {
  font-size: 13px;
  color: #6b7280;
}

.detail-row {
  margin-bottom: 4px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

/* 服务选择样式 */
.service-card.selected {
  border-color: #3b82f6;
  box-shadow: 0 2px 12px rgba(59, 130, 246, 0.15);
}

.service-select {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 10;
}

.service-header {
  position: relative;
}

/* 批量操作样式 */
.batch-actions-content {
  padding: 10px 0;
}

.selected-info {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: 20px 0;
}

.action-buttons .el-button {
  justify-content: flex-start;
  padding: 12px 20px;
  height: auto;
}

.batch-tips {
  margin-top: 20px;
}

/* 趋势指示器样式 */
.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  font-size: 12px;
}

.trend-icon {
  font-size: 14px;
}

.trend-icon.trend-up {
  color: #67c23a;
}

.trend-icon.trend-down {
  color: #f56c6c;
}

.trend-text {
  font-weight: 500;
}

/* 统计卡片点击效果 */
.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 分析对话框样式 */
.analysis-content {
  max-height: 70vh;
  overflow-y: auto;
}

.analysis-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

.analysis-charts {
  margin-bottom: 20px;
}

.chart-card {
  height: 300px;
}

.chart-container {
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  font-size: 14px;
}

.analysis-insights {
  margin-top: 20px;
}

.insights-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.insight-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #e5e7eb;
}

.insight-item .insight-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 16px;
  color: white;
}

.insight-item .insight-icon.success {
  background: #67c23a;
  border-left-color: #67c23a;
}

.insight-item .insight-icon.warning {
  background: #e6a23c;
  border-left-color: #e6a23c;
}

.insight-item .insight-icon.info {
  background: #409eff;
  border-left-color: #409eff;
}

.insight-content {
  flex: 1;
}

.insight-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #1f2937;
}

.insight-content p {
  margin: 0 0 8px 0;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

.insight-action {
  margin-top: 8px;
}

/* 服务详情对话框样式 */
.service-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.operation-stats {
  padding: 10px 0;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.stat-value {
  font-size: 14px;
  color: #333;
}

.stat-value.revenue {
  color: #f56c6c;
  font-weight: 600;
}

.service-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
}

.image-item {
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-item:hover {
  transform: scale(1.05);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-preview-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
  border-radius: 8px;
}

/* 高级筛选样式 */
.el-slider {
  margin: 20px 0;
}

/* 搜索框样式 */
.header-filters .el-input {
  margin-right: 10px;
}

/* 筛选标签样式 */
.filter-tags {
  margin: 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tag {
  background: #f0f9ff;
  color: #0369a1;
  border: 1px solid #bae6fd;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.filter-tag .close-btn {
  cursor: pointer;
  font-size: 14px;
  color: #64748b;
}

.filter-tag .close-btn:hover {
  color: #ef4444;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-filters {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .header-filters .el-input,
  .header-filters .el-select,
  .header-filters .el-button {
    width: 100%;
  }

  .services-grid {
    grid-template-columns: 1fr;
  }

  .service-actions {
    flex-wrap: wrap;
    gap: 4px;
  }

  .service-actions .el-button {
    flex: 1;
    min-width: 60px;
  }
}

/* 快速操作工具栏样式 */
.quick-actions-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-count {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.el-button-group .el-button {
  border-radius: 0;
}

.el-button-group .el-button:first-child {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

.el-button-group .el-button:last-child {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

/* 快速操作卡片样式 */
.quick-actions-card {
  margin-bottom: 20px;
  border: 1px solid #e5e7eb;
}

.quick-actions-card .el-card__body {
  padding: 16px 20px;
}

/* 优化服务网格布局 */
.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-top: 10px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #9ca3af;
}

.empty-state .empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  color: #d1d5db;
}

.empty-state .empty-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #6b7280;
}

.empty-state .empty-description {
  font-size: 14px;
  margin-bottom: 24px;
  color: #9ca3af;
}

/* 加载状态优化 */
.services-list-card .el-loading-mask {
  border-radius: 8px;
}

/* 服务卡片悬停效果优化 */
.service-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.service-card.selected:hover {
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
}
</style>
